const Router = require("koa-router");
const route = new Router();
const Mongoose = require("mongoose");

// http://106.12.132.55:27017/
const conn = Mongoose.createConnection(
  "mongodb://106.12.132.55:27017/liuting",
  {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  }
);

conn.on("open", console.log.bind(console, "连接成功！！"));
conn.on("error", console.log.bind(console, "连接失败！！"));

let Schema = new Mongoose.Schema({
  list: Number | String,
  createAt: {
    type: Date,
    default: Date.now,
  },
});

let Product = conn.model("liutings", Schema);

route.get("/", (ctx, next) => {
  ctx.body = "normal";
});

route.get("/test", (ctx, next) => {
  ctx.body = "test";
});

route.get("/create", async (ctx, next) => {
  let res = await Product.create({ list: ctx.query.a || "这是新创建的" });
  ctx.body = res;
});

route.get("/find", async (ctx, next) => {
  let res = await Product.find();
  ctx.body = res;
});

route.get("/clear", async (ctx, next) => {
  let res = await Product.deleteOne({ list: ctx.query.a || "test" });
  ctx.body = res;
});

module.exports = route;
